<template>
  <div class="tpl-container">
    <div class="mb20 condition-container">
      <div class="condition">
        <span class="color_494949 ft12 pr5">商品编码：</span>
        <ElInput
          v-model="Code"
          class="w164 mr14"
          placeholder="请输入商品编码"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">商品名称：</span>
        <ElInput
          v-model="Name"
          class="w164 mr14"
          placeholder="请输入商品名称"
        />
      </div>
      <div class="condition">
        <ElButton class="settingBtn" type="primary" @click="search">
          查询
        </ElButton>
        <ElButton
          v-if="MenuAuth('add')"
          class="settingBtn"
          type="primary"
          @click="addFn"
        >
          新增
        </ElButton>
        <ElButton class="settingBtn" type="primary" @click="exportList">
          导出商品
        </ElButton>
        <el-upload
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :action="action"
          :before-upload="beforeUpload"
          class="ml"
          :headers="headers"
          name="fileInput"
          :on-error="handleError"
          :on-success="handleSuccess"
          :show-file-list="false"
        >
          <ElButton type="primary">导入商品</ElButton>
        </el-upload>
        <ElButton
          class="settingBtn ml"
          type="primary"
          @click="downLoadTemplate"
        >
          下载模板
        </ElButton>
      </div>
    </div>
    <div class="table">
      <ElTable
        ref="multipleTableRef"
        v-loading="loading"
        :border="true"
        :data="tableData"
      >
        <!-- <ElTableColumn label="编号" prop="ID" width="auto" /> -->
        <ElTableColumn label="商品编码" prop="Code" width="auto" />
        <ElTableColumn label="内部编码" prop="InnerCode" width="auto" />
        <ElTableColumn label="商品名称" prop="Name" width="auto" />
        <ElTableColumn label="规格" prop="Spec" width="auto" />
        <ElTableColumn label="单位" prop="Unit" width="auto" />
        <ElTableColumn label="价格" prop="Price" width="auto" />
        <ElTableColumn label="原价格" prop="OriginPrice" width="auto" />
        <ElTableColumn label="会员价" prop="VipPrice" width="auto" />
        <ElTableColumn label="原产地" prop="Origin" width="auto" />
        <ElTableColumn label="块图">
          <template #default="{ row }">
            <div class="img-container">
              <ElImage
                fit="contain"
                :hide-on-click-modal="true"
                :initial-index="9"
                :preview-src-list="[row.BlockImage]"
                :src="row.BlockImage"
                :z-index="99999"
                :zoom-rate="1.2"
              />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="自定义图">
          <template #default="{ row }">
            <div class="img-container">
              <ElImage
                fit="contain"
                :hide-on-click-modal="true"
                :initial-index="9"
                :preview-src-list="[row.CustomImage]"
                :src="row.CustomImage"
                :z-index="99999"
                :zoom-rate="1.2"
              />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="状态">
          <template #default="{ row }">
            <div>
              {{ row.Status == 0 ? '禁用' : '正常' }}
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn label="是否同步">
          <template #default="{ row }">
            <div>
              {{ row.IsSync == false ? '否' : '是' }}
            </div>
          </template>
        </ElTableColumn> -->
        <ElTableColumn label="操作" width="200">
          <template #default="{ row }">
            <ElButton
              v-if="MenuAuth('edit')"
              link
              type="primary"
              @click="editFn(row)"
            >
              修改
            </ElButton>
            <ElButton
              v-if="MenuAuth('delete')"
              link
              type="danger"
              @click="deleteFn(row)"
            >
              删除
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-if="total > 0" class="pagination">
        <ElPagination
          background
          :current-page="searchInfo.pageNo"
          :layout="layout"
          :page-size="searchInfo.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { MenuAuth } from '~/src/utils/permission'
  import {
    productsPageData,
    delpro,
    Export,
    DownLoadTemplate,
  } from '@/api/mupro'
  import router from '@/router'
  import { useUserStore } from '@/store/modules/user'
  import { baseURL } from '@/config'
  import { parseTime } from '@/utils'
  const Code = ref('')
  const Name = ref('')
  const searchInfo = reactive({
    pageNo: 1,
    pageSize: 20,
    tableName: '',
    sort: '',
    order: '',
    wheres: `[{"name":"Code","value":${Code.value},"displayType":"like"}, {"name":"Name","value":${Name.value},"displayType":"like"}]`,
    export: false,
    value: '',
  })
  const loading = ref(false)
  const addFn = async () => {
    router.push({ path: `/mupro/detail` })
  }

  const layout = ref('total, sizes, prev, pager, next, jumper')
  const tableData = ref([])
  const total = ref(0)
  // 获取表格数据
  const gettableData = async () => {
    loading.value = true
    const { data } = await productsPageData(searchInfo)
    loading.value = false
    // console.log(data)
    tableData.value = data?.rows || []
    total.value = data?.total || 0
  }
  gettableData()
  //分页条数切换
  const handleSizeChange = (val: any) => {
    searchInfo.pageSize = val
    gettableData()
  }
  //分页切换
  const handleCurrentChange = (val: any) => {
    searchInfo.pageNo = val
    gettableData()
  }

  const search = () => {
    searchInfo.pageNo = 1
    if (Code.value.trim() !== '' || Name.value.trim() !== '') {
      const arr = []
      Code.value.trim() !== '' &&
        arr.push({ name: 'Code', value: Code.value, displayType: 'like' })
      Name.value.trim() !== '' &&
        arr.push({ name: 'Name', value: Name.value, displayType: 'like' })
      searchInfo.wheres = JSON.stringify(arr)
    } else {
      searchInfo.wheres = `[{"name":"Code","value": '',"displayType":"like"}, {"name":"Name","value": '',"displayType":"like"}]`
    }
    gettableData()
  }
  const editFn = (row: any) => {
    router.push({ path: `/mupro/detail`, query: { ID: row.ID } })
  }
  const $baseConfirm = inject('$baseConfirm') as any
  const deleteFn = async (row: any) => {
    $baseConfirm('你确定要删除当前项吗', null, async () => {
      await delpro({
        id: row.ID,
      })
      gettableData()
    })
  }
  // 导出
  const exportList = async () => {
    loading.value = true
    const data = await Export(searchInfo)
    const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
    downloadFile(data, `商品信息${time}`)
    loading.value = false
  }
  // 下载模板
  const downLoadTemplate = async () => {
    const data = await DownLoadTemplate()
    const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
    downloadFile(data, `商品模板${time}`)
  }
  // 下载文件
  const downloadFile = async (data: any, name: string) => {
    const blob = new Blob([data])
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.download = `${name}.xlsx`
    link.href = url
    link.click()
  }
  // 导入商品
  const { token } = useUserStore()
  const headers = reactive({ Authorization: `Bearer ${token}` })
  const action = ref(`${baseURL}/Products/Import`)
  const beforeUpload = () => {}
  const handleSuccess = async (response: any) => {
    if (response.code == 200) {
      gettableData()
    } else {
      let message = response.message
      if (response.code === '-1') {
        message = `${JSON.parse(response.data)?.join(',')}${message}`
      }
      ElMessage.error(message)
    }
  }
  const handleError = () => {}
</script>

<style lang="scss" scoped>
  .tpl-container {
    .color_494949 {
      color: #494949;
    }

    .noData {
      text-align: center;
      font-size: 16px;
      color: gray;
    }
    .w164 {
      width: 164px;
    }
    .mb20 {
      margin-bottom: 20px;
    }

    .img-container {
      display: flex;
      // justify-content: center;

      .img {
        width: 100px;
      }
    }

    .condition-container {
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .condition {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        margin-right: 14px;
        margin-bottom: 12px;
      }
    }

    .ml {
      margin-left: 10px;
    }
  }
  .el-table {
    & ::v-deep th.el-table__cell,
    ::v-deep td.el-table__cell {
      // 设置position 使得 子元素不与其产生新的层叠关系
      position: static;
    }
  }
</style>
